package com.example.receiptocr.viewModels

import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.receiptocr.data.TokenDataStore
import com.example.receiptocr.api.ReceiptApi
import com.example.receiptocr.bodys.responseBodys.ReceiptInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.math.BigDecimal
import javax.inject.Inject

// 票据UI状态数据类
data class ReceiptUiState(
    val receiptName: String = "",
    val sellerName: String = "",
    val receiptDate: String = "",
    val totalAmount: String = ""
)

// 票据列表状态
sealed class ReceiptsState {
    object Loading : ReceiptsState()
    object Empty : ReceiptsState()
    data class Success(val receipts: List<ReceiptInfo>) : ReceiptsState()
    data class Error(val message: String) : ReceiptsState()
}

@HiltViewModel
class ReceiptViewModel @Inject constructor(
    private val tokenDataStore: TokenDataStore,
    private val receiptApi: ReceiptApi
) : ViewModel() {
    private val TAG = "ReceiptViewModel"

    private val _receiptsState = mutableStateOf<ReceiptsState>(ReceiptsState.Loading)
    val receiptsState: State<ReceiptsState> = _receiptsState

    private val _expenseChartState = mutableStateOf<ExpenseChartState>(ExpenseChartState.Loading)
    val expenseChartState: State<ExpenseChartState> = _expenseChartState

    init {
        loadReceipts()
        loadWeeklyExpenses()
    }

    fun loadReceipts() {
        viewModelScope.launch {
            try {
                _receiptsState.value = ReceiptsState.Loading
                Log.d(TAG, "开始加载票据数据")

                val token = tokenDataStore.getTokenSync()
                if (token == null) {
                    _receiptsState.value = ReceiptsState.Error("请先登录")
                    Log.d(TAG, "未找到token")
                    return@launch
                }

                val response = receiptApi.getRecentReceipts()
                val receipts = response.map { receiptInfo ->
                    ReceiptInfo(
                        receiptId = receiptInfo.receiptId,
                        receiptName = receiptInfo.receiptName ?: "未知类型",
                        receiptCode = receiptInfo.receiptCode,
                        receiptNumber = receiptInfo.receiptNumber,
                        receiptDate = receiptInfo.receiptDate ?: "未知日期",
                        purchaserName = receiptInfo.purchaserName,
                        purchaserCode = receiptInfo.purchaserCode,
                        purchaserAddress = receiptInfo.purchaserAddress,
                        purchaserBank = receiptInfo.purchaserBank,
                        sellerName = receiptInfo.sellerName ?: "未知商家",
                        sellerCode = receiptInfo.sellerCode,
                        sellerAddress = receiptInfo.sellerAddress,
                        sellerBank = receiptInfo.sellerBank,
                        totalAmount = receiptInfo.totalAmount ?: 0.0,
                        note = receiptInfo.note,
                        receiptDataList = receiptInfo.receiptDataList
                    )
                }

                if (receipts.isEmpty()) {
                    _receiptsState.value = ReceiptsState.Empty
                } else {
                    _receiptsState.value = ReceiptsState.Success(receipts)
                }
                Log.d(TAG, "数据加载成功: ${receipts.size} 条记录")

            } catch (e: Exception) {
                Log.e(TAG, "加载票据数据失败", e)
                _receiptsState.value = ReceiptsState.Error(e.message ?: "未知错误")
            }
        }
    }

    fun loadWeeklyExpenses() {
        viewModelScope.launch {
            try {
                _expenseChartState.value = ExpenseChartState.Loading
                val token = tokenDataStore.getTokenSync()
                
                if (token.isNullOrEmpty()) {
                    _expenseChartState.value = ExpenseChartState.Error("请先登录")
                    return@launch
                }

                // 打印token用于调试
                Log.d("ReceiptViewModel", "Token before request: $token")
                
                // 确保token没有额外的空格或换行符
                val cleanToken = token.trim()
                val response = receiptApi.getWeeklyExpenses()
                
                _expenseChartState.value = if (response.isEmpty()) {
                    ExpenseChartState.Empty
                } else {
                    ExpenseChartState.Success(response)
                }
            } catch (e: Exception) {
                Log.e("ReceiptViewModel", "Error loading weekly expenses", e)
                when {
                    e.message?.contains("JWT") == true -> {
                        // Token无效，清除token并提示重新登录
                        viewModelScope.launch {
                            tokenDataStore.clearToken()
                        }
                        _expenseChartState.value = ExpenseChartState.Error("登录已过期，请重新登录")
                    }
                    else -> _expenseChartState.value = ExpenseChartState.Error("加载数据失败，请重试")
                }
            }
        }
    }
}

